import axios from 'axios';
import Keycloak from 'keycloak-js';

async function initKeycloak() {
  const keycloak = new Keycloak();
  console.log('set keycloak');
  await keycloak.init({onLoad: 'login-required'});
  return keycloak.token;
}

$(document).ready(async function () {
  var str = window.location.search;
  var definition_id = str.substring(4, str.length);
  var definition_xml;
  var token = await initKeycloak();
  /*
  axios.create({withCredentials: true}).get(
    'http://localhost/camunda/engine-rest/process-definition/'+definition_id+'/xml', 
    {headers: {'Content-Type':'application/json', 'Authorization':'Basic cm95Ok9yYW5nZTcqJTg='}}
    ).then(
      res=>{  
        var viewer = new BpmnViewer({
          container: '#diagram'
        });
        definition_xml = res.data.bpmn20Xml;
        viewer.importXML(definition_xml);
        var canvas = viewer.get('canvas');
        canvas.zoom('fit-viewport');
      }
    )
  */
    axios.create({withCredentials: true}).get(
      'http://localhost/camunda/engine-rest/process-definition/'+definition_id+'/diagram', 
      {headers: {'Authorization':'Bearer '+token}}
      ).then(
        res=>{  
          var svgdata = 'data:image/svg+xml;base64,'+window.btoa(unescape(encodeURIComponent(res.data)));
          $('#diagram').prop("src", svgdata);
        }
      )
  //console.log(definition_xml);
  //viewer.importXML(definition_xml);
  axios.create({withCredentials: true}).get(
    'http://localhost/camunda/engine-rest/history/process-instance?processDefinitionId='+definition_id, 
    {headers: {'Content-Type':'application/json', 'Authorization':'Bearer '+token}}
    ).then(
      res=>{
        console.log(res.data);
        $('#dataTable').DataTable({
          data: res.data,
          columns: [
            {
              data: "id",
              render: function(data) {
                return '<a href="' + 'processdetail.html?id=' + data + '&defid=' + definition_id + '">' + data + '</a>';
              }
            },
            {data: "processDefinitionName"},
            {data: "startTime"},
            {data: "endTime"},
            {data: "state"}
          ]
        });
      }
    )
});
  